import * as Cesium from 'cesium';
import BaseDraw from './common/BaseDraw';
import * as CesiumCoord from './common/CesiumCrood';
import * as CesiumCaculater from './common/CesiumCaculater';
import GroupEntityCollection from '../../Common/GroupEntityCollection';
import { v4 } from 'uuid';
/**
 * 派生类-绘制点- 计算两点之间的高度差
 */
export default class DrawPointHeight extends BaseDraw {
    constructor(viewer, tip) {
        super(viewer);
        this.viewer = viewer;
        this.tip = tip; // 提示DOM
        // 事件对象，每种类型的事件只能注册一次
        this.handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
        this.entityCollection = new GroupEntityCollection(viewer); // 集合
        this.ellipsoid = Cesium.Ellipsoid.WGS84;
    }
    resetDraw() {
        this.groupId = v4(); // 当次绘制的-id
        this.labelEntity = null; // 当次绘制的-圆实例
        this.pointEntity = null; // 当次绘制的-圆实例
        this.positionList = []; // 当次绘制的笛卡尔数组
    }
    getAllEntity() {
        return this.entityCollection.getAllEntities();
    }
    createPointEntity(cartesian) {
        const entity = new Cesium.Entity({
            position: cartesian, // 世界坐标
            point: {
                color: Cesium.Color.YELLOW,
                pixelSize: 5,
                disableDepthTestDistance: Number.POSITIVE_INFINITY,
            },
        });
        return entity;
    }
    createLabelEntity(cartesian, height) {
        const _this = this;
        return new Promise(async (resolve, reject) => {
            try {
                // 请求地形高程数据
                const entity = new Cesium.Entity({
                    position: cartesian, // 世界坐标
                    label: {
                        text: `高度差:${height.toFixed(2)}米`,
                        font: '20px',
                        color: Cesium.Color.RED,
                        pixelOffset: new Cesium.Cartesian2(0, -20),
                        fillColor: Cesium.Color.WHITE,
                        showBackground: true,
                        backgroundColor: Cesium.Color.BLUE,
                    },
                });
                resolve(entity);
            } catch (e) {
                console.error(e);
                reject(e);
            }
        });
    }
    // 计算两点高度差
    compuedHeight(point0, point1) {
        const p0 = this.ellipsoid.cartesianToCartographic(point0);
        const p1 = this.ellipsoid.cartesianToCartographic(point1);
        const height = Math.abs(p0.height - p1.height);
        return height;
    }
    createLabelEntity2(cartesian, pickedPosition) {
        return new Promise(async (resolve, reject) => {
            try {
                const cartographic = Cesium.Cartographic.fromCartesian(pickedPosition);
                // 请求地形高程数据
                let height = 0.0;
                if (this.viewer.terrainProvider) {
                    const updatedPositions = await Cesium.sampleTerrainMostDetailed(
                        this.viewer.terrainProvider,
                        [cartographic]
                    );
                    height = updatedPositions[0].height;
                }
                console.log(`点击位置的高程为：${height} 米`);
                const entity = new Cesium.Entity({
                    position: cartesian, // 世界坐标
                    label: {
                        text: `高度:${height}米`,
                        font: '20px',
                        color: Cesium.Color.RED,
                        pixelOffset: new Cesium.Cartesian2(0, -20),
                        fillColor: Cesium.Color.WHITE,
                        showBackground: true,
                        backgroundColor: Cesium.Color.BLUE,
                    },
                });
                resolve(entity);
            } catch (e) {
                console.error(e);
                reject(e);
            }
        });
    }
}
/**
 * 开始绘制点
 * @param {* 是否显示测量Label} showMeasureLabel
 * @param {* 是否连续绘制} continuousDraw
 */
DrawPointHeight.prototype.startDraw = function (showMeasureLabel = true, continuousDraw = true) {
    const _this = this;
    this.tip.show('单击开始绘制');
    this.resetDraw(); // 重置绘制中间量
    // 通过事件管理器新增事件 -左键单击事件
    this.handler.setInputAction(
        async event => {
            const cartesian = CesiumCoord.ScreenToCartesian3(_this.viewer, event.position); // 屏幕坐标转世界坐标
            if (!Cesium.defined(cartesian)) return;
            _this.positionList.push(cartesian.clone());
            const length = _this.positionList.length;
            if (length > 0 && length % 2 === 0) {
                console.log('偶数点');
                if (showMeasureLabel) {
                    // 每两个点，计算高度差
                    const height = _this.compuedHeight(
                        _this.positionList[length - 2],
                        _this.positionList[length - 1]
                    );
                    // 标注实体
                    _this.labelEntity = await _this.createLabelEntity(cartesian, height);
                    _this.addEntityCollection(_this.labelEntity); // 加入集合
                }
            }
            // 点实体
            _this.pointEntity = _this.createPointEntity(cartesian);
            _this.addEntityCollection(_this.pointEntity); // 加入集合

            if (!continuousDraw) {
                // 不连续绘制
                _this.endDraw();
            }
        },

        Cesium.ScreenSpaceEventType.LEFT_CLICK
    );
    // 通过事件管理器新增事件 -鼠标移动事件
    this.handler.setInputAction(
        event => {
            const { x, y } = event.endPosition;
            this.tip.moveTipDOMPosition(x, y); // 改变 TipDOM 位置
        },

        Cesium.ScreenSpaceEventType.MOUSE_MOVE
    );
    // 通过事件管理器新增事件 -右键单击事件
    this.handler.setInputAction(() => {
        _this.endDraw();
    }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
};

/**
 * 结束绘制点
 */
DrawPointHeight.prototype.endDraw = function () {
    if (this.positionList.length < 3) {
        // 删除这次绘制结果
        this.entityCollection.remove(this.groupId);
    }
    this.tip.close();
    // 移除绑定的事件
    this.handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
    this.handler.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE);
    this.handler.removeInputAction(Cesium.ScreenSpaceEventType.RIGHT_CLICK);
    this.resetDraw(); // 重置绘制中间量
};
/**
 * 清除绘制的点
 */
DrawPointHeight.prototype.removeDraw = function () {
    this.entityCollection.removeAll(); // 清空集合所有
};
